package com.chaihu.order;

import com.chaihu.core.cache.MappingCache;
import com.chaihu.order.service.CenterServiceCacheService;
import com.chaihu.service.init.ServiceStartInit;
import com.chaihu.utils.factory.ApplicationContextFactory;
import com.chaihu.utils.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

@Slf4j
@SpringBootApplication(scanBasePackages = {
        "com.chaihu.service.configuration",
        "com.chaihu.service.init",
        "com.chaihu.order",
        "com.chaihu.core",
        "com.chaihu.db"
})
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {
        "com.chaihu.intf.code",
        "com.chaihu.intf.user",
        "com.chaihu.intf.common"
})
public class OrderServiceApplicationStart {

    /**
     * 实例化RestTemplate，通过@LoadBalanced注解开启均衡负载能力.
     *
     * @return restTemplate
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
        StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        m.setWriteAcceptCharset(false);
        RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(m).build(RestTemplate.class);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        return restTemplate;
    }

    public static void main(String[] args) {
        try {
            ApplicationContext context = SpringApplication.run(OrderServiceApplicationStart.class, args);
            ServiceStartInit.initSystemConfig(context);

            //刷新缓存
            flushMainCache(args);
        } catch (Throwable e) {
            log.error("系统启动失败", e);
        }
    }

    /**
     * 刷新主要的缓存
     *
     * @param args
     */
    private static void flushMainCache(String[] args) {
        log.debug("判断是否需要刷新日志，参数 args 为 {}", args);

        //因为好多朋友启动时 不加 参数-Dcache 所以启动时检测 redis 中是否存在 chaihu_blog_version
        String mapping = MappingCache.getValue("chaihu_blog_version");
        if (StringUtil.isEmpty(mapping)) {
            CenterServiceCacheService centerServiceCacheService = (CenterServiceCacheService) ApplicationContextFactory.getBean("centerServiceCacheService");
            centerServiceCacheService.startFlush();
        }

        if (args == null || args.length == 0) {
            return;
        }
        for (int i = 0; i < args.length; i++) {
            if (args[i].equalsIgnoreCase("-Dcache")) {
                log.debug("开始刷新日志，入参为：{}", args[i]);
                CenterServiceCacheService centerServiceCacheService = (CenterServiceCacheService) ApplicationContextFactory.getBean("centerServiceCacheService");
                centerServiceCacheService.startFlush();
            }
        }
    }
}
